<?php
/**
 * User: Hunman
 * Date: 16.07.13
 * Time: 20:43
 */
class Model_Model
{
    //TODO один массив
    private $host = "goodligh.mysql.ukraine.com.ua";
    private $dbName = "goodligh_db";
    private $user = "goodligh_db";
    private $password = "LTNg9J2R";
    const currentWay = "/home/goodligh/goodlight.kiev.ua/test/";
    const cacheUrl  = "cache/";

    static $orderCategoryPrice = 0;
    static $orderCategoryName = 1;

    function __construct()
    {
    }

    /**
     * вызов подключения к БД
     * @return PDO
     */
    protected
    function dbh()
    {
//        echo "<span style = 'color: red'> connect to BD </span><br>";
        // TODO Проверка статус подключения базы
        return $this->dbConnect();
    }

    /**
     * подключение к БД
     * @return PDO
     */
    protected
    function dbConnect()
    {
        try {
            $db = new PDO("mysql:host=$this->host;dbname=$this->dbName", $this->user, $this->password);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->exec("set names utf8");
        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
        return $db;
    }

    /**
     * Формируем кеш
     * @param $key
     * @param array $data
     * @param $time
     * @return array
     */
    public function cache($key, $data = array(), $time = 86400 /*c*/)
    {
        $key = md5($key);
        //чтение
        if ($data == null)
        {
			$getCache = file_get_contents(self::currentWay . self::cacheUrl . $key . ".cache");
			$cacheArray = unserialize($getCache);
			if ($cacheArray["timeCacheLive"] != 2 && $cacheArray["timeCacheLive"] != 1 && $cacheArray["timeCacheLive"] < time())
			{
				$cacheArray =  null;
			}
			return $cacheArray;
        }
        //запись
        else 
        {
            $data["timeCacheLive"] =  time()+$time;
            $prepareData = serialize($data);
            file_put_contents(self::currentWay . self::cacheUrl . $key . ".cache", $prepareData );
        }

    }
}